<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="注意:只允许为第三级分类设置相关的参数"
        type="warning"
        center
        show-icon
      >
      </el-alert>
      <!-- 级联选择器 -->
      <el-row>
        <el-col>
          <span
            >选择商品分类:
            <el-cascader
              v-model="seleteKeys"
              :options="cateList"
              :props="cascaderOpt"
              @change="cascaderSelect"
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="small"
            :disabled="isBtnDisabled"
            @click="addFormDialogVisible = true"
            >动态按钮</el-button
          >
          <el-table :data="manyTableBata" border stripe style="width: 100%">
            <el-table-column align="center" type="expand">
              <!-- 循环渲染Tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增 -->
                <!-- @keyup.enter.native="handleInputConfirm"光标离开或enter -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column align="center" type="index"> </el-table-column>
            <el-table-column align="center" prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="toEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="small"
            :disabled="isBtnDisabled"
            @click="addFormDialogVisible = true"
            >静态按钮</el-button
          >
          <el-table :data="onlyTableBata" border stripe style="width: 100%">
            <el-table-column align="center" type="expand">
              <!-- 循环渲染Tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增 -->
                <!-- @keyup.enter.native="handleInputConfirm"光标离开或enter -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column align="center" type="index"> </el-table-column>
            <el-table-column align="center" prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="toEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + textTitle"
      :visible.sync="addFormDialogVisible"
      width="40%"
      @close="clearDialog"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog title="修改参数" :visible.sync="editDialogVisible" width="30%">
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsParams',
  data () {
    return {
      cateList: [], // 分类数据列表
      seleteKeys: [], // 选中的分类数组
      // 配置对象
      cascaderOpt: {
        expandTrigger: 'click',
        value: 'cat_id',
        label: 'cat_name'
      },
      activeName: 'many', // tab选中项
      manyTableBata: [],
      onlyTableBata: [],
      addFormDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      inputVisible: false, // 控制按钮文本框切换
      inputValue: '' // 文本框输入内容
    }
  },
  created () {
    // 调用获取分类列表方法
    this.getCateList()
  },
  methods: {
    // 获取分类数据方法
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.cateList = res.data
    },
    // 获取动态和静态参数方法{}
    async getTabsData () {
      // const index = this.seleteKeys.length - 1
      // const id = this.seleteKeys[index]
      // getId()
      const { data: res } = await this.$http.get(
        `categories/${this.getId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // console.log(res.data)
      // 遍历tag数据
      res.data.forEach(item => {
        // 边界问题
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      this.$message.success(res.meta.msg)
      if (this.activeName === 'many') {
        this.manyTableBata = res.data
      } else {
        this.onlyTableBata = res.data
      }
    },
    // 级联选择器改变时触发
    cascaderSelect () {
      if (this.seleteKeys.length !== 3) {
        this.seleteKeys = []
        this.manyTableBata = []
        this.onlyTableBata = []
        return false
      }
      this.getTabsData()
    },
    // tab切换时触发方法
    tabClick () {
      if (this.seleteKeys.length !== 3) return
      this.getTabsData()
    },
    clearDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击添加
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.getId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.addFormDialogVisible = false
        this.$message.success(res.meta.msg)
        this.getTabsData()
      })
    },
    // 根据 ID 查询参数
    async toEdit (paramsInfo) {
      const { data: res } = await this.$http.get(
        `categories/${this.getId}/attributes/${paramsInfo.attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑提交参数
    toParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.getId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getTabsData()
        this.editDialogVisible = false
      })
    },
    // 删除参数
    async deleteParams (paramsId) {
      const confimRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confimRes !== 'confirm') {
        return this.$message.error('取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.getId}/attributes/${paramsId.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getTabsData()
    },
    // 输入框切换触发事件
    async handleInputConfirm (role) {
      // 去除空格重置Tag框
      if (role.inputValue.trim().length === 0) {
        role.inputValue = ''
        role.inputVisible = false
        return false
      }
      // 将最新的值放入参数数组中
      role.attr_vals.push(role.inputValue)
      role.inputValue = ''
      role.inputVisible = false
      this.updateParams(role)
    },
    // Tag删除按钮
    handleClose (i, role) {
      role.attr_vals.splice(i, 1)
      this.updateParams(role)
    },

    async updateParams (role) {
      // 发起请求
      const { data: res } = await this.$http.put(
        `categories/${this.getId}/attributes/${role.attr_id}`,
        {
          attr_name: role.attr_name,
          attr_sel: this.activeName,
          attr_vals: role.attr_vals.join(' ') // 接口文档要求
        }
      )
      if (res.meta.status !== 200) {
        // 没有添加成功移除新添加项
        role.attr_vals.pop()
        return this.$message.error(res.meta.msg)
      }
      // 添加提示即可
      // 页面改变，数据同步到页面，刷新页面就可看到
      return this.$message.success(res.meta.msg)
    },
    // 点击按钮控制输入框显示
    showInput (role) {
      role.inputVisible = true
      // 修改数据之后立即使用这个方法，获取更新后的DOM
      // 数据更改之后，驱动UI发生改变
      // 但最新UI渲染需要一定时间
      // 如果直接获取DOM元素会失败
      // 需要DOM结构渲染好再执行某一操作
      // 就可以把这个操作放在 this.$nextTick内部
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    }
  },
  // 计算属性
  computed: {
    // 按钮隐藏
    isBtnDisabled () {
      if (this.seleteKeys.length !== 3) {
        return true
      }
      return false
    },
    // 添加静态属性和动态参数的文本
    textTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    getId () {
      if (this.seleteKeys.length !== 3) {
        return null
      }
      const index = this.seleteKeys.length - 1
      const id = this.seleteKeys[index]
      return id
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 30px;
}
.el-tabs {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
